import * as types from '../mutation-types'
import {getUserLogin} from 'api/login'
import {saveUserInfo, clearUserInfo, loadUserInfo} from 'common/js/cache'

const state = {
  userInfo: loadUserInfo(),
  confirmLogin: false
}

const getters = {
  userInfo: state => state.userInfo,
  confirmLogin: state => state.confirmLogin
}

// actions
const actions = {
  userLogin({commit}, val) {
    return getUserLogin(val).then((res) => {
      if (res.success === false) {
        return res
      } else {
        res.user_token = val
        commit(types.SET_USER_INFO, saveUserInfo(res))
        return res
      }
    })
  },
  LoginOut({commit}) {
    commit(types.SET_USER_INFO, clearUserInfo())
  },
  checkConfirmLogin({commit}, val) {
    commit(types.SET_CONFIRM_LOGIN, val)
  }
}

// mutations
const mutations = {
  [types.SET_USER_INFO](state, val) {
    state.userInfo = val
  },
  [types.SET_CONFIRM_LOGIN](state, val) {
    state.confirmLogin = val
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
